<?php
namespace Plugin;

class Verify
{

    public static $width  = 120;
    public static $height = 40;
    public static $len    = 4;
    public static $font   = null;
    // 生成输出验证码
    public static function OutCode($key = "0")
    {
        empty(self::$font) && self::$font = __DIR__ . DS . "Verify" . DS . "font.ttc";
        header("Content-Type:image/jpeg");
        //验证码的长度
        $img      = imagecreatetruecolor(self::$width, self::$height);
        $bg_color = imagecolorallocate($img, rand(200, 255), rand(200, 255), rand(200, 255));
        imagefill($img, 0, 0, $bg_color);
        $str  = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'L', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
        $code = '';
        for ($i = 0; $i < self::$len; $i++) {
            $k = rand(0, 35);
            $code .= $str[$k];
            $color  = imagecolorallocate($img, rand(0, 100), rand(0, 100), rand(0, 100));
            $result = imagefttext($img, rand(15, 30), rand(-30, 30), 8 + 30 * $i, 33, $color, self::$font, $str[$k]);
        }
        $_SESSION['code' . $key] = $code;
        for ($i = 0; $i < 10; $i++) {
            $green = imagecolorallocate($img, rand(100, 255), rand(150, 255), rand(200, 255));
            imageline($img, mt_rand(0, self::$width - 1), mt_rand(0, self::$height - 1), mt_rand(0, self::$width - 1), mt_rand(0, self::$height - 1), $green);
        }
        for ($i = 0; $i < 300; $i++) {
            $red = imagecolorallocate($img, rand(80, 200), rand(90, 150), rand(200, 255));
            imagesetpixel($img, mt_rand(0, self::$width - 1), mt_rand(0, self::$height - 1), $red);
        }
        imagejpeg($img);
        $data = ob_get_clean();
        ob_clean();
        //$data =  file_get_contents('php://input');
        imagedestroy($img);
        return ['code' => "data:image/jpeg;base64," . base64_encode($data), 'state' => "ok"];
    }
    // 验证验证码
    public static function CheckCode($code, $key = "0")
    {
        return (isset($_SESSION['code' . $key]) && (strcasecmp($_SESSION['code' . $key], $code) == 0));
    }

}
